package zsc.ruanc.practicaltraining.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.lettuce.core.ScriptOutputType;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zsc.ruanc.practicaltraining.exception.ApiException;
import zsc.ruanc.practicaltraining.mapper.*;
import zsc.ruanc.practicaltraining.model.domain.TArticle;
import zsc.ruanc.practicaltraining.model.domain.TComment;
import zsc.ruanc.practicaltraining.model.domain.TReply;
import zsc.ruanc.practicaltraining.model.domain.TUser;
import zsc.ruanc.practicaltraining.model.vo.CommentVo;
import zsc.ruanc.practicaltraining.service.CommentService;
import zsc.ruanc.practicaltraining.utils.IPUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ReplyMapper replyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private StatisticMapper statisticMapper;

    /**
     *  插入一条评论
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public int insertComment(TComment vo, String name, String ip) {
        TArticle article = articleMapper.getArticle(vo.getArticleId());

        if (article.getFlag() == null) { // 文章不存在
            throw new ApiException(404);
        } else if (article.getFlag() == false) { // 文章没通过审核
            throw new ApiException(-13, "文章还未开放");
        }

        if (article.getAllowComment() == false) {
            throw new ApiException(-1, "作者设置此文章不能评论");
        }

        vo.setCreated(new Date());

        vo.setAuthor(name);
        vo.setIp(ip);
        int x = commentMapper.insert(vo);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String address = IPUtils.address(ip);
                    commentMapper.updateAddress(vo.getId(), address);
                } catch (Exception e) {
                    System.out.println("address设置失败");
                    e.printStackTrace();
                }
            }
        }).start();

        statisticMapper.commentsAndOne(vo.getArticleId()); // 评论数加一

        return vo.getId();
    }

    /**
     * 删除一条评论
     * @param commentId
     * @return
     */
    @Override
    @Transactional
    public boolean deleteComment(int commentId, String author) {




        TComment comment =commentMapper.selectOne(commentId);



        int x = commentMapper.delete(commentId, author);

        if (x == 0) {
            throw new ApiException(-1, "删除失败");
        }
        statisticMapper.commentsCutOne(comment.getArticleId()); // 评论数减一


        return true;
    }

    @Override
    public boolean updateComment(TComment vo, String author, String ip) {
        if (vo.getId() == null) {
            throw new ApiException(400, "id不能为空");
        }

        vo.setCreated(new Date());
        vo.setIp(ip);
        vo.setAuthor(author);
        int x = commentMapper.update(vo);
        if (x == 0) {
            throw new ApiException(-1, "修改失败");
        }

        return true;
    }

    /**
     * 分页 查询评论 包括评论的回复
     * @param cur
     * @param size
     * @param articleId
     * @return
     */
    @Override
    public Map selectPage(int cur, int size, int articleId, boolean flag) {

        TArticle article = articleMapper.getArticle(articleId);

        if (article.getAllowComment() == false) {
            throw new ApiException(-1, "作者设置文章不允许评论， 所有无法获取评论");
        }

        // 分页查询评论
        PageHelper.startPage(1, 10).setOrderBy("id desc");
        //不包含ip信息
        PageInfo<CommentVo> commentPageInfo = new PageInfo<>(this.commentMapper.selectPage(articleId, flag));

        Map map = new HashMap();

        List<CommentVo> list = commentPageInfo.getList();

        map.put("total", commentPageInfo.getTotal());
        map.put("list", list);

        return map;
    }


    /**
     *  评论点赞
     * @param commentId
     * @return
     */
    @Override
    public boolean likesAndOneComment(int commentId) {
        int x = commentMapper.likesAndOneComment(commentId);
        if (x == 0) { // 评论不存在
            throw new ApiException(-1, "评论不存在");
        }



        return true;
    }
    @Override
    public boolean likesCutOneComment(int commentId) {
        int x = commentMapper.likesCutOneComment(commentId);
        if (x == 0) { // 评论不存在 或者 点赞数为0
            throw new ApiException(-1, "评论不存在 或者 点赞数为0");
        }
        return true;
    }

    //----------回复功能----------------------------------------


    /**
     *  插入一条回复
     * @param vo
     * @param fromName
     * @param ip
     * @return
     */
    @Transactional
    public int insertReply(TReply vo, String fromName, String ip) {

        boolean b = replyMapper.checkFromName(vo.getCommentId(), vo.getToName());


        TComment comment = commentMapper.selectOne(vo.getCommentId()); // 查询是否有那条评论



        if (comment == null) {
            throw new ApiException(-1, "你是爬虫吧, 没有此评论");
        }
        if (b == false && !comment.getAuthor().equals(vo.getToName())) {
            // 被你评论的人的名字必须出现在评论或者回复中
            throw new ApiException(-1, "你是爬虫吧, 没找toName");
        }



        vo.setFromName(fromName);
        vo.setIp(ip);
        vo.setCreated(new Date());

        replyMapper.insert(vo);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String address = IPUtils.address(ip);
                    replyMapper.updateAddress(vo.getId(), address);
                } catch (Exception e) {
                    System.out.println("address设置失败");
                    e.printStackTrace();
                }
            }
        }).start();

        statisticMapper.commentsAndOne(comment.getArticleId()); // 评论加一
        return vo.getId();
    }

    /**
     * 删除一条评论
     * @param id
     * @param author
     * @return
     */
    @Transactional
    public boolean deleteReply(int id, String author) {

        TReply reply = replyMapper.selectOne(id); // 查询那条回复

        if (reply == null) {
            throw new ApiException(-1, "你是爬虫吧");
        }

        int x = replyMapper.delete(id, author);
        if (x == 0) {
            throw new ApiException(-13, "你没有权限删除");
        }

        TComment comment = commentMapper.selectOne(reply.getCommentId());
        statisticMapper.commentsCutOne(comment.getArticleId()); // 评论减一

        return true;
    }

    /**
     * 点赞 | 取消
     * @param replyId
     * @return
     */
    public boolean likesAndOneReply(int replyId) {
        int x = replyMapper.likesAndOne(replyId);
        if (x == 0) { // 评论不存在
            throw new ApiException(-1, "评论不存在");
        }
        return true;
    }

    /**
     * 点赞 | 取消
     * @param replyId
     * @return
     */
    public boolean likesCutOneReply(int replyId) {
        int x = replyMapper.likesCutOne(replyId);

        if (x == 0) { // 评论不存在 或者 点赞数为0
            throw new ApiException(-1, "评论不存在 或者 点赞数为0");
        }
        return true;

    }

    /**
     * 管理员管理评论
     * @param cur
     * @param size
     * @return
     */
    public Map adminSelectPage(int cur, int size) {

        PageHelper.startPage(cur, size);

        PageInfo<CommentVo> info = new PageInfo<>(this.commentMapper.adminSelectPage());

        Map map = new HashMap();

        map.put("total", info.getTotal());

        List<CommentVo> list = info.getList();
        for(CommentVo i : list) {
            i.setArticleName(articleMapper.getArticleTitle(i.getComment().getId()));
        }
        map.put("list", list);

        return map;

    }




//    public boolean updateReply(TReply vo, int userId, String ip) {
//
//        String fromName = userMapper.selectNameByUserId(userId); // 发起者名字
//        TUser user = userMapper.selectByName(vo.getToName()); // 查询是否有这个人
//        TReply tReply = replyMapper.selectOne(vo.getId()); // 查询是否有这条回复
//        if (user == null || tReply == null) {
//            throw new ApiException(-1, "你是爬虫吧");
//        }
//
//        vo.setCreated(new Date());
//        vo.setIp(ip);
//        vo.setFromName(fromName);
//
//
//
//
//    }






}
